package com.asseco.mio.codex.controllers;

import com.asseco.mio.codex.Municipality;
import com.asseco.mio.codex.Founder;
import com.asseco.mio.codex.GeoArea;
import com.asseco.mio.codex.Industry;
import com.asseco.mio.codex.Institution;
import com.asseco.mio.codex.InstitutionForm;
import com.asseco.mio.core.model.AuditLog;
import com.asseco.mio.core.webapp.controller.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.commons.lang.StringUtils;
import org.appfuse.service.GenericManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.Constants;
import org.springframework.validation.Validator;

@Controller
@RequestMapping("/institutionform*")
public class InstitutionFormController extends BaseFormController {

    private GenericManager<GeoArea, String> geoAreaManager = null;
    private GenericManager<Municipality, String> municipalityManager = null;
    private GenericManager<Founder, String> founderManager = null;
    private GenericManager<Industry, String> industryManager = null;
    private GenericManager<Institution, String> institutionManager = null;
    private GenericManager<AuditLog, String> auditLoggerManager = null;
    @Autowired(required = false)
    Validator validator;

    @Autowired
    public void setInstitutionManager(@Qualifier("institutionManager") GenericManager<Institution, String> institutionManager) {
        this.institutionManager = institutionManager;
    }

    @Autowired
    public void setMunicipalityManager(@Qualifier("municipalityManager") GenericManager<Municipality, String> municipalityManager) {
        this.municipalityManager = municipalityManager;
    }

    @Autowired
    public void setGeoAreaManager(@Qualifier("geoAreaManager") GenericManager<GeoArea, String> geoAreaManager) {
        this.geoAreaManager = geoAreaManager;
    }

    @Autowired
    public void setFounderManager(@Qualifier("founderManager") GenericManager<Founder, String> founderManager) {
        this.founderManager = founderManager;
    }

    @Autowired
    public void setIndustryManager(@Qualifier("industryManager") GenericManager<Industry, String> industryManager) {
        this.industryManager = industryManager;
    }

    @Autowired
    public void setAuditLoggerManager(GenericManager<AuditLog, String> auditLoggerManager) {
        this.auditLoggerManager = auditLoggerManager;
    }

    public InstitutionFormController() {
        setCancelView("redirect:institutions");
        setSuccessView("redirect:institutions");
    }

    @ModelAttribute
    public InstitutionForm institutionForm() {

        InstitutionForm x = new InstitutionForm(this.getAllActiveMunicipality(this.municipalityManager.getAll()), this.getAllActiveGeoArea(this.geoAreaManager.getAll()), this.getAllActiveIndustry(this.industryManager.getAll()), this.getAllActiveFounder(this.founderManager.getAll()));

        return x;
    }

    @RequestMapping( method = {RequestMethod.GET, RequestMethod.POST})
    protected InstitutionForm showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String userString = request.getRemoteUser();
        try {
            if (!request.isUserInRole(Constants.ADMIN_ROLE)) {
                throw new Exception("");
            }

        } catch (Exception e) {

            response.sendRedirect("/MIO/mainMenu");
        }
        String id = request.getParameter("id");
        if (!StringUtils.isBlank(id)) {
            InstitutionForm x = this.institutionForm();
            x.setInstitution(institutionManager.get(id));

            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "institutionform", "institutions.show", institutionManager.get(id).getInstitutionName(),
                    "", request.getRemoteHost(), new Date()));
            return x;
        }

        return this.institutionForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(InstitutionForm instForm2, BindingResult errors, HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        if (request.getParameter("cancel") != null) {
            return getCancelView();
        }

        if (validator != null) { // validator is null during testing
            validator.validate(instForm2, errors);

            if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
                return "institutionform";
            }
        }
        log.debug("entering 'onSubmit' method...");

        boolean isNew = (instForm2.getInstitution().getId().equals(""));
        String success = getSuccessView();
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "institutionform", "institutions.delete", instForm2.getInstitution().getInstitutionName(),
                    "", request.getRemoteHost(), new Date()));
            institutionManager.remove(instForm2.getInstitution().getId());
            saveMessage(request, getText("person.deleted", locale));

        } else {

            institutionManager.save(instForm2.getInstitution());
            String key = (isNew) ? "institution.added" : "institution.updated";
            saveMessage(request, getText(key, locale));
            auditLoggerManager.save(new AuditLog(request.getRemoteUser(), "institutionform", key, instForm2.getInstitution().getInstitutionName(),
                    "test", request.getRemoteHost(), new Date()));
            if (!isNew) {
                success = "redirect:institutionform?id=" + instForm2.getInstitution().getId();
            }
        }

        return success;
    }

    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        super.initBinder(request, binder);
        SimpleDateFormat dateFormat =
                new SimpleDateFormat(getText("dd/MM/yyyy", request.getLocale()));
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, null, new CustomDateEditor(dateFormat, true));
    }

    public List getAllActiveMunicipality(List<Municipality> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Municipality ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveGeoArea(List<GeoArea> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            GeoArea ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveIndustry(List<Industry> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Industry ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }

    public List getAllActiveFounder(List<Founder> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Founder ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}
